const bookshelf = require("./bookshelf");

class Mysql_booksheif {
  constructor(tableName) {
    this.Model = bookshelf.Model.extend({
      tableName,
    });
  }
  /**fetchPage分页查询
   * params
   * @param {Object} where 条件
   * @param {Number} pageSize 每页显示条数
   * @param {Number} page 当前页
   */
  fetchPage(params = {}) {
    return new Promise((resolve, reject) => {
      new this.Model()
        .where(params.where ? params.where : {})
        .fetchPage({
          pageSize: params.pageSize || 10,
          page: params.page || 1,
        })
        .then((model) => {
          resolve({
            code: 200,
            message: "查询成功",
            data: {
              total: model.pagination.rowCount,
              list: model,
            },
          });
        })
        .catch((err) => {
          reject({
            code: 500,
            message: "查询失败",
            data: err,
          });
        });
    });
  }
  /**fetchAll 查询所以
   * @param {Object} where 条件
   */
  fetchAll(where) {
    return new Promise((resolve, reject) => {
      new this.Model()
        .where(where ? where : {})
        .fetchAll()
        .then((model) => {
          resolve({
            code: 200,
            message: "查询成功",
            data: {
              total: model.length,
              list: model,
            },
          });
        })
        .catch((err) => {
          console.log(err);
          reject({
            code: 500,
            message: "查询失败",
            data: err,
          });
        });
    });
  }
  /**delete 删除
   * @param {Object} where 条件
   */
  delete(where) {
    return new Promise((resolve, reject) => {
      new this.Model()
        .where(where ? where : {})
        .destroy()
        .then((model) => {
          console.log(model);
          resolve({
            code: 200,
            message: "删除成功",
            data: null,
          });
        })
        .catch((err) => {
          console.log(err);
          reject({
            code: 500,
            message: "删除失败",
            data: err,
          });
        });
    });
  }
  /**save 添加更新
   * @param {Object} where 条件
   * @param {Object} data 数据
   */
  insert_update(params) {
    if (!Boolean(params.where)) {
      params.where = {};
    }
    return new Promise((resolve, reject) => {
      new this.Model()
        .where(JSON.stringify(params.where) != "{}" ? params.where : {})
        .save(params.data, {
          patch: JSON.stringify(params.where) != "{}" ? true : false,
        })
        .then((model) => {
          resolve({
            code: 200,
            message:
              JSON.stringify(params.where) != "{}" ? "修改成功" : "添加成功",
            data: null,
          });
        })
        .catch((err) => {
          reject({
            code: 500,
            message:
              JSON.stringify(params.where) != "{}" ? "修改失败" : "添加失败",
            data: err,
          });
        });
    });
  }
}

module.exports = Mysql_booksheif;
